package za.org.foobar.famon.reporter;

import org.apache.log4j.Logger;

import java.util.Calendar;

/**
*
*/
public class FamonReporterPollThread implements Runnable {
    private static final Logger log = Logger.getLogger(FamonReporterPollThread.class);
    private FamonFileBufferWorkProcessor processor;
    private boolean running;

    public FamonReporterPollThread(FamonFileBufferWorkProcessor processor) {
        this.processor = processor;
    }

    public void stop() {
        running = false;
    }

    public void run() {
        final int dayEnd = 24*60;
        int t = processor.getPollStartTime();
        int hourStart = (int)Math.floor(t / 100);
        int start = hourStart * 60 + t - hourStart * 100;
        int end = start + processor.getPollDurationMinutes();
        int amStart = Math.max(end - dayEnd, 0);
        end = Math.min(end, dayEnd);

        running = true;
        while (running) {
            try {
                Calendar calNow = Calendar.getInstance();
                int now = calNow.get(Calendar.HOUR) * 60 + calNow.get(Calendar.MINUTE);
//                    log.debug("Start = " + start + ", end = " + end + ", amStart = " + amStart + " dayEnd = " + dayEnd + ", now = " + now);
                if ((start <= now && now <= end) || now <= amStart) {
                    // Send messages and sleep if there weren't any
                    if (!processor.sendBufferedFailures()) {
                        log.info("Sleeping " + processor.getPollSleepSeconds() + " seconds");
                        Thread.sleep(processor.getPollSleepSeconds()*1000);
                    }
                } else {
                    int min = now < start ? start - now : dayEnd + start - now;
                    log.info("Not time to poll, sleeping for " + min + " minutes");
                    Thread.sleep(min * 60 * 1000);
                }
            } catch (Exception e) {
                log.error("Got exception", e);
            }
        }
    }
}
